package com.rem.concurrency.juc.my15Lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 自旋锁测试
 *
 * @author Rem
 * @date 2021-03-11
 */

public class SpinlockTest {

    public static void main(String[] args) {
        MySpinlock lock = new MySpinlock();

        new Thread(() -> {
            lock.mylock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        }, "X").start();

        new Thread(() -> {
            lock.mylock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        }, "V").start();
    }
}

/**
 * 自定义自旋锁
 */
class MySpinlock {

    private AtomicReference<Thread> threadAtomicReference = new AtomicReference<>();


    public void mylock() {

        Thread thread = Thread.currentThread();
        System.err.println(thread.getName());

        //cas的自旋 比较如果为空就放入本线程
        while (threadAtomicReference.compareAndSet(null, thread)) {

        }
    }

    public void myUnlock() {

        Thread thread = Thread.currentThread();
        System.err.println(thread.getName());

        //如果有本线程 就释放
        threadAtomicReference.compareAndSet(thread, null);

    }
}
